package com.wwwarehouse.resource_center.fragment.maintenanceunit;


import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.eventbus_event.BackListenerEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.maintenanceunit.UpdateUnitBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.RefreshEvent;
import com.wwwarehouse.resource_center.eventbus_event.UnitEvent;
import com.wwwarehouse.resource_center.utils.ByteUnits;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;

/**
 * Creator by zhenwang.xiang on 2017/10/13 14:02
 * Description: 新增单位
 */

@Route(path = ResourceConstant.PATH_NEWUNIT_FRAGMENT)
public class NewUnitFragment extends BaseFragment {
    private TextInputLayout mUnitNameInputLayout, mUnitSymbolInputLayout;
    private ClearEditText mUnitNameEditText, mUnitSymbolEditText;
    private EditText mDescribeEditText;
    private Button mConfirmBtn;
    private boolean isErrorName = false, isErrorPhone = false;
    private int mFlag = 0;
    private UpdateUnitBean mUnitBean;
    String mUserId;
    private Handler mHandler = new Handler();
    CardDeskFunctionResponseBean.TaskBean mTaskBean;
    String ownerUkid = "";
    private boolean mIsFresh = false;
    private String from;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_new_unit, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        ((BaseActivity) mActivity).hideSoftByEditViewIds(new int[]{R.id.cet_unit_name, R.id.cet_unit_symbol, R.id.et_unit_describe});
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof NewUnitFragment)
            if (mFlag == 1) {
                mActivity.setTitle(getString(R.string.update_unit));
            } else {
                mActivity.setTitle(getString(R.string.add_unit));
            }
    }

    @Override
    public void requestDatas() {
    }

    private void initView() {
        mUnitNameInputLayout = $(R.id.til_unit_name);
        mUnitSymbolInputLayout = $(R.id.til_unit_symbol);
        mUnitNameEditText = $(R.id.cet_unit_name);
        mUnitSymbolEditText = $(R.id.cet_unit_symbol);
        mDescribeEditText = $(R.id.et_unit_describe);
        mConfirmBtn = $(R.id.btn_confirm);

        mUserId = sp.getValue(Constant.sp_User_Id);
        if (getArguments() != null) {
            from = getArguments().getString("from");
            mFlag = getArguments().getInt("flag");
            mIsFresh = getArguments().getBoolean("refresh");
            mUnitBean = (UpdateUnitBean) getArguments().getSerializable("unit");
            mTaskBean = (CardDeskFunctionResponseBean.TaskBean) getArguments().getSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS);
            if (mTaskBean != null) {
                ownerUkid = mTaskBean.getBusinessId();
            } else {
                ownerUkid = getArguments().getString("ownerUkid");
            }
        }

        if (mFlag == 1) {
            if (mUnitBean != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("unitName", mUnitBean.getUnitName());
                NoHttpUtils.httpPost(ResourceConstant.GET_BYUNITNAME, map, mOnResponseListener, 2);
            }
        }
        mUnitNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String name = mUnitNameEditText.getText().toString();
                int destLen = ByteUnits.getCharacterNum(name);
                if (destLen > 8) {
                    isErrorName = true;
                    mUnitNameInputLayout.setStateWrong(getString(R.string.unit_name_wrong));
                } else {
                    int lenth = name.length();
                    if ((!checkMarkRule(name, "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")) && lenth > 0) {
                        isErrorName = true;
                        mUnitNameInputLayout.setStateWrong(getString(R.string.unit_name_tips));
                    } else {
                        isErrorName = false;
                        mUnitNameInputLayout.setStateNormal();
                    }
                }
                setButtonState();
            }
        });
        mUnitNameEditText.setOnMyFocusChangeListener(new ClearEditText.onMyFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                String unitname = mUnitNameEditText.getText().toString().trim();
                if (!b) {
                    if (isErrorName == false && unitname.length() > 0) {
                        if (mFlag != 1) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("unitName", unitname);
                            NoHttpUtils.httpPost(ResourceConstant.EXISTED_UNITNAME, map, mOnResponseListener, 0);
                        }
                    }
                }
            }
        });
        mUnitSymbolEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String symbo = mUnitSymbolEditText.getText().toString();
                int destLen = ByteUnits.getCharacterNum(symbo);
                if (destLen > 8) {
                    isErrorPhone = true;
                    mUnitSymbolInputLayout.setStateWrong(getString(R.string.unit_chrat_wrong));
                } else {
                    int lenth = symbo.length();
                    if ((!checkMarkRule(symbo, "^[^0-9\\u4e00-\\u9fa5]+$")) && lenth > 0) {
                        isErrorPhone = true;
                        mUnitSymbolInputLayout.setStateWrong(getString(R.string.unit_symbol_tips));
                    } else {
                        isErrorPhone = false;
                        mUnitSymbolInputLayout.setStateNormal();
                    }
                }
                setButtonState();
            }
        });
        mConfirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String unitname = mUnitNameEditText.getText().toString().trim();
                String unitcharacter = mUnitSymbolEditText.getText().toString().trim();
                String comment = mDescribeEditText.getText().toString().trim();
                Map<String, Object> map = new HashMap<>();
                if (mFlag == 1) {
                    map.put("ownerUkid", mUnitBean.getOwnerUkid());
                    map.put("comment", comment);
                    map.put("unitName", unitname);
                    map.put("unitCharacter", unitcharacter);
                    map.put("unitUkid", mUnitBean.getUnitUkid());
                    map.put("userId", mUserId);
                    NoHttpUtils.httpPost(ResourceConstant.UPDATE_UNIT, map, mOnResponseListener, 3);
                } else {
                    map.put("ownerUkid", ownerUkid);
                    map.put("comment", comment);
                    map.put("unitName", unitname);
                    map.put("unitCharacter", unitcharacter);
                    map.put("userId", mUserId);
                    NoHttpUtils.httpPost(ResourceConstant.INSERT_UNIT, map, mOnResponseListener, 1);
                }
            }
        });
    }


    /**
     * Description: 判断是否显示按钮
     */
    private void setButtonState() {
        String name = mUnitNameEditText.getText().toString().trim();
        if (!TextUtils.isEmpty(name) && isErrorName == false && isErrorPhone == false) {
            mConfirmBtn.setEnabled(true);
            mConfirmBtn.setBackgroundResource(R.drawable.common_btn2_solid_selector);
        } else {
            mConfirmBtn.setEnabled(false);
            mConfirmBtn.setBackgroundResource(R.drawable.common_btn1_noclick_shape);
        }
    }

    /**
     * Description: 判断是否匹配,传入字符串和正则表达式
     */

    public static boolean checkMarkRule(String name, String regex) {
        Pattern pattern = Pattern.compile(regex);
        return pattern.matches(regex, name);
    }

    public int getmFlag() {
        return mFlag;
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            if ("0".equals(commonClass.getCode())) {
                switch (what) {
                    case 0:
                        Boolean data = (Boolean) commonClass.getData();
                        if (data) {
                            isErrorName = true;
                            mUnitNameInputLayout.setStateWrong(getString(R.string.unit_name_have_save));
                            setButtonState();
                        }
                        break;
                    case 1:
                        toast(getString(R.string.unit_save_success));
                        if (from != null && !from.isEmpty()) {
                            popFragment();
                            EventBus.getDefault().post(new RefreshEvent("UnitRefresh"));

                        } else {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    popFragment();
                                    if (mIsFresh) {
                                        EventBus.getDefault().post(new UnitEvent("update"));
                                    }
                                }
                            }, 2000);
                        }
                        break;
                    case 2:
                        UpdateUnitBean updateUnitBean = JSON.parseObject(commonClass.getData().toString(), UpdateUnitBean.class);
                        if (updateUnitBean != null) {
                            if (!TextUtils.isEmpty(updateUnitBean.getUnitName())) {
                                mUnitNameEditText.setText(updateUnitBean.getUnitName());
                            }
                            if (!TextUtils.isEmpty(updateUnitBean.getUnitCharacter())) {
                                mUnitSymbolEditText.setText(updateUnitBean.getUnitCharacter());
                            }
                            if (!TextUtils.isEmpty(updateUnitBean.getComment())) {
                                mDescribeEditText.setText(updateUnitBean.getComment());
                            }

                        }
                        break;
                    case 3:
                        toast(getString(R.string.unit_update_success));
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                popFragment();
                                EventBus.getDefault().post(new UnitEvent("update"));
                            }
                        }, 2000);
                        break;
                }
            } else if ("70902".equals(commonClass.getCode())) {
                DialogTools.getInstance().showCustomWarning(getContext(), "提示", "该单位正在被使用，请稍后再尝试。", true, null);
            } else {
                toast(commonClass.getMsg());
            }
        }

        @Override
        public void onFailed(String result, int what) {
        }

        @Override
        public void onFinish(int what) {

        }
    };

    public void onEventMainThread(BackListenerEvent event) {
        String message = event.getMsg();
        if (message.equals("NewUnitFragment")) {
            if (mFlag != 1) {
                DialogTools.getInstance().showTCDialog(getContext(), "提示", "返回将不会保存已输入的内容，确认返回吗？", "继续编辑", "不保存，返回", null, new DialogTools.DismissListener() {
                    @Override
                    public void setDismissListener(Dialog dialog, View view) {
                        dialog.dismiss();
                        popFragment();
                    }
                });
            } else {
                popFragment();
            }
        }
    }
}
